/*
 *
 * ============================================================================
 *
 *       Filename:  main.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2014年07月09日 17时29分44秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  zkk(zkk), zkk@126.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>  
#include <unistd.h>  
#include <errno.h>
#include <string.h>
#include <sys/types.h>  
#include <sys/ioctl.h>
#include <sys/file.h>
#include <fcntl.h>
#include <sys/stat.h>  
#include <time.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <mosquitto.h>
#include <sys/select.h>

#include "include/log.h"
#include "include/arg.h"
#include "include/common.h"
#include "include/mqtt_client.h"

#define BUF_SIZE 512

static int one_instance()
{
	char path[BUF_SIZE] = {0};
	sprintf(path, "/var/run/switch_esim.pid");
	printf("path %s\n", path);

	int pid_file = open(path, O_CREAT | O_RDWR | O_CLOEXEC, 0666);
	int rc = flock(pid_file, LOCK_EX | LOCK_NB);
	if(rc) {
		if(EWOULDBLOCK == errno) {
			sys_warn("another program is running\n");
			return -1;
		}
	}
	return 0;
}

static int setnonblocking(int fd)
{
	int flags;
	if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
		flags = 0;
	}
	return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}

int main(int argc, char *argv[])
{

	proc_args(argc, argv);
	if(one_instance() < 0)
		return 0;

	if(daemon_mode)
		daemon(0, 0);

	printf("start ! ======\n");
	struct mymqtt *mymq = create_mqtt(args_info.id_arg,
				args_info.clean_session_flag, NULL);
	if(!mymq) {
		sleep(1);
		printf("connet mqtt server failed\n");
		exit(-1);
	}

	while(1) {
		printf("while ===========\n");
		struct timeval tv;
		tv.tv_sec = 6;
		select(0, NULL, NULL, NULL, &tv);
	}

	return 0;
}
